﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Albums;
using SIG.Model;
using SIG.Model.Albums;
using SIG.Model.Enums;
using SIG.Resources.Admin;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Albums;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class AlbumController : BaseController
    {
        private readonly IAlbumService _albumService;

        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public AlbumController(IAlbumService albumService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _albumService = albumService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;

        }
        // GET: Admin/Album

        #region Album

        public ActionResult Index(int? page, string keyword)
        {
            AlbumListVM albumListVM = GetElements(page, keyword);

            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(albumListVM);

            //List<AlbumVM> vm = GetAlbumList();
            //return View(vm);
        }

        private AlbumListVM GetElements(int? page, string keyword)
        {
            var albumListVM = new AlbumListVM();

            albumListVM.Keyword = keyword;
            albumListVM.PageIndex = (page ?? 1) - 1;
            albumListVM.PageSize = SettingsManager.Album.PageSize;
            int totalCount;
            var specialistlist = _albumService.GetPagedElements(albumListVM.PageIndex, albumListVM.PageSize, albumListVM.Keyword, out totalCount);
            var specialistVMList = _mapper.Map<List<Album>, List<AlbumVM>>(specialistlist);
            albumListVM.TotalCount = totalCount;
            albumListVM.Albums = new StaticPagedList<AlbumVM>(specialistVMList, albumListVM.PageIndex + 1, albumListVM.PageSize, albumListVM.TotalCount); ;
            return albumListVM;
        }

        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/AlbumSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        [HttpGet]
        public ActionResult Add()
        {
            var vAlbum = new AlbumIM();
            vAlbum.Active = true;
            //vAlbum.Importance = 0;

            return PartialView("_Add", vAlbum);
        }



        [HttpPost]
        public JsonResult Add(AlbumIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newAlbum = _mapper.Map<AlbumIM, Album>(vm);
            _albumService.Create(newAlbum);

            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {
                var pageMeta = new PageMeta()
                {
                    ObjectId = newAlbum.Id,
                    Keyword = vm.Keywords.Replace('，', ','),
                    Description = vm.SEODescription,
                    ModelType = ModelType.ALBUM
                };
                _pageMetaService.Create(pageMeta);
            }

            int count;
            var pageSize = SettingsManager.Album.PageSize;
            var list = _albumService.GetPagedElements(0, pageSize, string.Empty, out count);
            List<AlbumVM> categories = _mapper.Map<List<Album>, List<AlbumVM>>(list);
            AR.Data = RenderPartialViewToString("_AlbumList", categories);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Album));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Album album = _albumService.GetById(id);
            if (album == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<AlbumIM>(album);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.ALBUM, album.Id);
            if (pageMeta != null)
            {
                vm.Keywords = pageMeta.Keyword;
                vm.SEODescription = pageMeta.Description;
            }

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(AlbumIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newAlbum = _mapper.Map<AlbumIM, Album>(vm);
            _albumService.Update(newAlbum);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.ALBUM, vm.Id);
            pageMeta = pageMeta ?? new PageMeta();


            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {

                pageMeta.ObjectId = vm.Id;
                pageMeta.Keyword = vm.Keywords;
                pageMeta.Description = vm.SEODescription;
                pageMeta.ModelType = ModelType.ALBUM;

                if (pageMeta.Id > 0)
                {
                    _pageMetaService.Update(pageMeta);
                }
                else
                {
                    _pageMetaService.Create(pageMeta);
                }
            }

            var album = _mapper.Map<AlbumVM>(newAlbum);
            AR.Id = album.Id;
            AR.Data = RenderPartialViewToString("_AlbumItem", album);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Album));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Album vAlbum = _albumService.GetById(id);

            if (vAlbum.Photos.Any())
            {
                AR.Setfailure("此分类下面还有文章存在，不能删除！");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _albumService.Delete(vAlbum);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Album));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vAlbum = _albumService.GetById(id);
            if (vAlbum == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vAlbum.Active = !vAlbum.Active;
                _albumService.Update(vAlbum);

                var vm = _mapper.Map<AlbumVM>(vAlbum);

                AR.Data = RenderPartialViewToString("_AlbumItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Album));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        //[AllowAnonymous]
        //public JsonResult IsSeoNameUnique(string seoName, int? Id)
        //{
        //    return !IsExist(seoName, Id)
        //        ? Json(true, JsonRequestBehavior.AllowGet)
        //        : Json(false, JsonRequestBehavior.AllowGet);
        //}
        //[AllowAnonymous]
        //public bool IsExist(string seoName, int? id)
        //{
        //    var wType = _albumService.GetAll().Where(w => w.SeoName == seoName);
        //    if (id > 0)
        //    {
        //        wType = wType.Where(w => w.Id != id);
        //    }

        //    if (wType.Count() > 0)
        //        return true;

        //    return false;
        //}



        #endregion
    }
}